/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package meshindexer.XMLParser;

import java.io.StringBufferInputStream;
import java.io.StringReader;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;

/**
 *
 * @author Dallaz
 */
public class MedlineParser {

    protected String url;
    Document doc;

    private class NoOpEntityResolver implements EntityResolver {

        public InputSource resolveEntity(String publicId, String systemId) {
            return new InputSource(new StringBufferInputStream(""));
        }
    }

    public MedlineParser(String url) throws Exception {
        this.url = url;
        SAXBuilder sax = new SAXBuilder();
        sax.setEntityResolver(new NoOpEntityResolver());
        try {
            doc = (Document) sax.build(url);
            doc = sax.build(new StringReader(doc.getRootElement().getValue()));
        } catch (Exception ex) {
        }
    }

    public String getAbstract() {
        Element root = doc.getRootElement();
        String abs = parseChildren(root, "AbstractText");
        if (abs != null) {
            return abs;
        } else {
            return "The article contains no abstract";
        }
    }

    public String getTitle() {
        Element root = doc.getRootElement();
        String abs = parseChildren(root, "ArticleTitle");
        if (abs != null) {
            return abs;
        } else {
            return "The article has no title";
        }
    }

    public String getAuthors() {
        return null;
    }

    private String parseChildren(Element root, String searchFor) {
        if (root.getName().equalsIgnoreCase(searchFor)) {
            return root.getValue();
        } else {
            for (Object e : root.getChildren()) {
                if (e instanceof Element) {
                    if (parseChildren((Element) e, searchFor) != null) {
                        return parseChildren((Element) e, searchFor);
                    }
                }
            }
        }
        return null;
    }
}


